<template>
  <a-card :bordered="false">
    <div class="container">
      <div class="one-third-width">
        <div>
          <!-- 选择工作站 -->
          <div style="margin-bottom: 16px">
            <j-dict-select-tag
              v-model="receiveStation"
              dictCode="basic_station_info,station_name,station_code"
              placeholder="请选择工作站"
              style="width: 200px;"
            />
          </div>
          <a-button
            type="link"
            size="large"
            style="margin-left: 65%;"
            :disabled="refreshButtonDisabled"
            @click="handleSelectedStation(receiveStation)"
            >{{ buttonText }}</a-button
          >
        </div>
        <div style="text-align: center; font-weight: 700; font-size: 20px">{{ shelfCode }}{{ shelfFace }}</div>
        <div class="grid-container" :style="{ gridTemplateColumns: getColumnStyle }">
          <div
            class="grid-item"
            v-for="item in dataList"
            :key="item.id"
            :style="{ backgroundColor: item.color }"
            @click="getCompartmentUtilization(item)"
          >
            <div class="grid-item-content">{{ item.compartmentCode }}</div>
          </div>
        </div>
        <div class="line1"></div>
        <!-- 延生线 -->
        <div class="line2"></div>
        <!-- 延生线 -->
      </div>
      <div class="two-third-width">
        <div>
          <!-- 货架 -->
          <label for="customer-select" class="select-label">货架号 : </label>
          <input
            type="text"
            class="select-box"
            v-model="compartmentCode"
            ref="compartmentCodeInput"
            @keyup="handleScanGoodsShelves"
          />
          <!-- 标签号输入 -->
          <label for="customer-select" class="select-label" style="margin-left: 30px">标签号 : </label>
          <input type="text" class="select-box" v-model="tag_number" ref="tagNumberInput" @keyup="handleScanSku" />
        </div>
        <div class="top">
          <div class="top-bar">
            <!-- 这里放置顶栏内容 -->
          </div>
          <div class="table-wrapper">
            <a-table :columns="columns" :data-source="dataSource" :scroll="{ y: 400 }" :pagination="ipagination">
              <template slot="action" slot-scope="text, record">
                <a-button type="primary" size="small" @click="reduceInventory(record)">
                  库存箱数-1
                </a-button>
              </template>
              <template slot="availableGoodsQuantity" slot-scope="text, record">
                <div>
                  <a-input-number
                    v-model="record.availableGoodsQuantity"
                    style="display: inline-block; width: 50%"
                  ></a-input-number>
                  <a @click="updateGoodsQuantity(record)" style="display: inline-block; width: 25%">同步</a>
                </div>
              </template>
            </a-table>
          </div>
        </div>
        <div>
          <a-button type="primary" icon="file-sync" @click="rotate" v-show="dataList.length">转面</a-button>
          <a-button
            type="primary"
            icon="file-add"
            @click="releaseShelf"
            v-show="dataList.length"
            style="margin-left: 100px"
            >放行</a-button
          >
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { getAction, postAction } from '../../../api/manage'

export default {
  name: 'Test',
  data() {
    return {
      refreshButtonDisabled: false, // 控制刷新按钮是否可用
      refreshButtonCountdown: 5, //刷新按钮的倒计时
      refreshButtonTimer: null, // 刷新按钮的定时器
      receiveStation: undefined, // 已选择的工作站编码
      compartment: {}, // 当前选中的货格对象
      compartmentCode: '', // 当前选中的货格编码
      tag_number: '', // 标签号
      expandedRowRender: '',
      basicShelf: {}, // 当前货架对象
      basicShelfType: {}, // 当前货架类型对象
      compartmentList: [], // 当前货格列表
      shelfCode: '',
      shelfFace: '',
      colNum: 1,
      dataList: [],
      dataSource: [],
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '品番编码',
          align: 'center',
          dataIndex: 'skuCode',
          disabled: true
        },
        {
          title: '箱数',
          align: 'center',
          dataIndex: 'availableBoxQuantity',
          disabled: true
        },
        {
          title: '件数',
          key: 'availableGoodsQuantity',
          align: 'center',
          dataIndex: 'availableGoodsQuantity',
          //   disabled: true,
          scopedSlots: { customRender: 'availableGoodsQuantity' }
        },
        {
          title: '标签号',
          align: 'center',
          dataIndex: 'labelNumber',
          disabled: true
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'action' } // 使用 scoped slot 来渲染自定义内容
        }
      ],
      ipagination: {
        pageSizeOptions: ['10', '20', '200', '1000'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true
      },
      url: {
        getIpAddress: '/inOrder/inOrder/getIpAddress', // 获取客户端ip地址
        getInOrderShelf: '/inOrder/inOrder/getInOrderShelf', //查询当前工作站的入库任务及任务货架
        getDoingOrder: '/inOrder/inOrder/getDoingOrder', // 当前登录人正在进行中的任务
        enter: '/inOrder/inOrder/noOrderScanCode', // 扫码入库
        reportLabelEdit: '/inOrder/inOrder/noOrderReduceInventory',
        rotate: '/inOrder/inOrder/rotate/', //货架转面
        getBasicCompartmentReportLabel: '/reportLabel/reportLabel/getBasicCompartmentReportLabel',
        releaseShelf: '/inOrder/inOrder/releaseShelf/', //货架放行
        updateGoodsQuantity: '/inOrder/inOrder/noOrderUpdateGoodsQuantity' // 更新件数
      },
      superFieldList: []
    }
  },
  created() {
    this.getSuperFieldList()
    this.chooseStation()
  },
  mounted() {
    this.expandedRowRender = 'expandedRowRender'
    // 设置货架输入框初始焦点
    this.$nextTick(() => {
      this.$refs.compartmentCodeInput.focus()
    })
  },
  computed: {
    buttonText() {
      return this.refreshButtonDisabled ? `${this.refreshButtonCountdown}秒后可刷新` : '刷新当前货架'
    },
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    getColumnStyle() {
      if (this.colNum === 1) {
        return '1fr'
      } else {
        return `repeat(${this.colNum}, 1fr)`
      }
    }
  },
  methods: {
    chooseStation() {
      postAction(this.url.getIpAddress).then(res => {
        if (res.success) {
          switch (res.result) {
            case '192.168.10.86':
              this.receiveStation = 1
              break
            case '192.168.10.222':
              this.receiveStation = 2
              break
            case '192.168.10.75':
              this.receiveStation = 3
              break
          }
        }
      })
    },
    // 刷新当前货架
    handleSelectedStation() {
      if (!this.receiveStation) {
        this.showErrorModel('请选择工作站')
        return
      }
      this.countdownRefreshButton()
      // 根据所选工作站，查询对应货架
      postAction(this.url.getInOrderShelf + '?stationCode=' + this.receiveStation)
        .then(res => {
          if (res.success) {
            let data = res.result
            this.basicShelf = data.basicShelf
            this.basicShelfType = data.basicShelfType
            this.compartmentList = data.compartmentList
            this.shelfFace = data.shelfFace

            this.shelfCode = this.basicShelf.shelfCode
            this.colNum = this.basicShelfType.colums
          } else {
            this.showErrorModel(res.message)
          }
          this.drawCompartment()
          this.$refs.compartmentCodeInput.focus() // 将焦点移到货架号输入框
        })
        .catch(e => {
          console.log(e.message)
        })
    },
    drawCompartment() {
      // 渲染货格
      // 将列表按每层显示的格数分成对应的小组
      let compartmentList = this.compartmentList
      let colNum = this.colNum
      const chunks = []
      for (let i = 0; i < compartmentList.length; i += colNum) {
        chunks.push(compartmentList.slice(i, i + colNum))
      }
      // 对集合进行倒序排列
      const chunksList = []
      const reversedChunks = chunks.reverse()
      for (let i = 0; i < reversedChunks.length; i++) {
        chunksList.push(...reversedChunks[i])
      }
      const list = chunksList.map(chunk => {
        chunk.color = 'lightgreen'
        return chunk
      })
      this.dataList = list
    },
    // 监听货架号输入框
    handleScanGoodsShelves(event) {
      // 按了回车
      if (event && event.key === 'Enter') {
        this.compartmentCode = this.lastCharToLower(this.compartmentCode)
        this.scanCompartment()
      }
    },
    // 监听标签号输入框
    handleScanSku(event) {
      // 按了回车
      if (event && event.key === 'Enter') {
        // 获取扫码枪扫描到的数据
        const scanData = event.target.value
        this.tag_number = scanData
        this.queryQRCode()
      }
    },
    // 入库
    queryQRCode() {
      //if (this.tag_number.indexOf(this.shelfCode) != -1) {
      //    this.compartmentCode = this.lastCharToLower(this.tag_number)
      //    this.tag_number = undefined
      //    this.scanCompartment()
      //    return
      //}
      if (this.compartmentCode == null || this.compartmentCode == '') {
        this.tag_number = undefined
        this.showErrorModel('请先选择货格')
        return
      }

      const param = new FormData()
      param.append('labelNumber', this.tag_number)
      param.append('compartmentCode', this.compartmentCode)
      postAction(this.url.enter, param)
        .then(res => {
          if (res.success) {
            this.scanCompartment()
          } else {
            this.showErrorModel(res.message)
          }
        })
        .catch(error => {
          this.showErrorModel(error)
        })
        .finally(() => {
          this.tag_number = undefined
        })
    },
    // 库存减1
    reduceInventory(record) {
      let param = new FormData()
      param.append('id', record.id)
      postAction(this.url.reportLabelEdit, param).then(res => {
        if (res.success) {
          this.showSuccessModel(res.message)
          this.scanCompartment()
        } else {
          this.showErrorModel(res.message)
        }
      })
    },
    // 更新件数
    updateGoodsQuantity(record) {
      let param = new FormData()
      param.append('id', record.id)
      param.append('goodsQuantity', record.availableGoodsQuantity)
      postAction(this.url.updateGoodsQuantity, param).then(response => {
        if (response.success) {
          this.showSuccessModel(response.message)
          this.scanCompartment()
        } else {
          this.showErrorModel(response.message)
        }
      })
    },
    getCompartmentUtilization(obj) {
      // 点击货格
      this.compartment = obj
      this.compartmentCode = obj.compartmentCode
      this.scanCompartment()
    },
    scanCompartment() {
      this.dataList.forEach(e => {
        if (this.compartmentCode === e.compartmentCode) {
          e.color = 'lightblue'
        } else {
          e.color = 'lightgreen'
        }
      })
      postAction(this.url.getBasicCompartmentReportLabel + '?compartmentCode=' + this.compartmentCode).then(res => {
        if (res.success) {
          this.dataSource = res.result
          console.log(this.dataSource)
          this.$refs.tagNumberInput.focus() // 将焦点移到标签号输入框
        } else {
          this.showErrorModel(res.message)
        }
      })
    },
    rotate() {
      //货架转面
      this.countdownRefreshButton()
      this.refreshButtonDisabled = true
      let face = this.shelfFace == 'F' ? 'B' : 'F'
      let code = this.receiveStation + '/' + face
      console.log(code)
      getAction(this.url.rotate + code)
        .then(res => {
          if (res.success) {
            this.dataList = []
            this.compartmentList = []
            this.getDoingOrder()
            this.showSuccessModel('转面成功')
          } else {
            this.showErrorModel(res.message)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    releaseShelf() {
      //货架放行
      this.countdownRefreshButton()
      getAction(this.url.releaseShelf + this.receiveStation)
        .then(res => {
          if (res.code === 200) {
            this.dataList = []
            this.compartmentList = []
            this.getDoingOrder()
            this.showSuccessModel('放行成功')
          } else {
            this.showErrorModel(res.message)
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'customerCode', text: '客户', dictCode: '' })
      fieldList.push({ type: 'string', value: 'customerName', text: '客户名称', dictCode: '' })
      fieldList.push({ type: 'string', value: 'skuCode', text: '品番', dictCode: '' })
      fieldList.push({ type: 'string', value: 'backNo', text: '背番', dictCode: '' })
      fieldList.push({ type: 'string', value: 'number', text: '数量', dictCode: '' })
      fieldList.push({ type: 'string', value: 'labelNumber', text: '标签号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'inWorkNumber', text: '进库作业号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'invoiceNumber', text: '发票号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'batchNumber', text: '批次号', dictCode: '' })
      fieldList.push({ type: 'datetime', value: 'stackingDate', text: '上架日期' })
      fieldList.push({ type: 'string', value: 'rackNo', text: '原始箱号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'shelfCode', text: '货架', dictCode: '' })
      fieldList.push({ type: 'string', value: 'compartmentCode', text: '货格', dictCode: '' })
      fieldList.push({ type: 'string', value: 'isTwoSided', text: '货架朝向', dictCode: '' })
      fieldList.push({ type: 'string', value: 'status', text: '状态', dictCode: '' })
      fieldList.push({ type: 'string', value: 'outWorkNumber', text: '出库作业号', dictCode: '' })
      fieldList.push({ type: 'datetime', value: 'outDate', text: '出库日期' })
      this.superFieldList = fieldList
    },
    lastCharToLower(str) {
      //把字符串最后一位字母转成小写
      if (str.length === 0) {
        return str // 如果字符串为空，直接返回
      }
      // 获取最后一个字符并转换为小写
      const lastChar = str[str.length - 1].toLowerCase()
      // 获取除最后一个字符之外的其余部分
      const restOfStr = str.slice(0, -1)
      // 拼接新的字符串
      return restOfStr + lastChar
    },
    showSuccessModel(message) {
      this.speakMessage(message)

      let secondsToGo = 5
      const modal = this.$success({
        title: `对话框将在 ${secondsToGo} 秒后自动关闭。`,
        content: message
      })
      const interval = setInterval(() => {
        secondsToGo -= 1
        modal.update({
          title: `对话框将在 ${secondsToGo} 秒后自动关闭。`
        })
      }, 1000)
      setTimeout(() => {
        clearInterval(interval)
        modal.destroy()
      }, secondsToGo * 1000)
    },
    showErrorModel(message) {
      // 语音播报错误信息
      this.speakMessage(message)

      let secondsToGo = 5
      const modal = this.$error({
        title: `对话框将在 ${secondsToGo} 秒后自动关闭。`,
        content: '出错了！错误内容：' + message
      })
      const interval = setInterval(() => {
        secondsToGo -= 1
        modal.update({
          title: `对话框将在 ${secondsToGo} 秒后自动关闭。`
        })
      }, 1000)
      setTimeout(() => {
        clearInterval(interval)
        modal.destroy()
      }, secondsToGo * 1000)
    },
    speakMessage(message) {
      if ('speechSynthesis' in window) {
        const utterance = new SpeechSynthesisUtterance(message)
        utterance.lang = 'zh-CN' // 设置语言为中文
        speechSynthesis.speak(utterance)
      } else {
        console.warn('当前浏览器不支持语音合成')
      }
    },
    countdownRefreshButton() {
      this.refreshButtonDisabled = true
      this.refreshButtonTimer = setInterval(() => {
        this.refreshButtonCountdown--
        if (this.refreshButtonCountdown <= 0) {
          clearInterval(this.refreshButtonTimer)
          this.refreshButtonDisabled = false
          this.refreshButtonCountdown = 5
        }
      }, 1000)
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>
<style scoped>
.container {
  overflow: hidden;
  /* 清除浮动 */
}

.one-third-width {
  float: left;
  width: 30%;
}

.two-third-width {
  float: right;
  width: 68%;
}

.top {
  height: 65vh;
  flex-direction: column;
  border: 1px solid #ccc;
  /* 添加外边框 */
  padding: 0px;
  /* 添加内边距，使内容与边框有一定距离 */
  margin-bottom: 20px;
  /* 添加下边距 */
}

.top-bar {
  height: 50px;
  background-color: #f0f0f0;
}

.table-wrapper {
  flex: 1;
  overflow: auto;
}

.grid-container {
  display: grid;
  grid-auto-rows: 100px;
  grid-gap: 0;
  justify-items: center;
  box-sizing: border-box;
  border: 10px solid #000000;
}

.grid-item {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid #0c0c0c;
  padding: 10px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.line1 {
  width: 5%;
  height: 80px;
  background-color: #070707;
  /* 延生线颜色 */
  margin-top: -30px;
  /* 调整延生线与图形之间的间距 */
}

.line2 {
  width: 5%;
  height: 80px;
  background-color: #070707;
  /* 延生线颜色 */
  margin-top: -80px;
  /* 调整延生线与图形之间的间距 */
  margin-left: calc(95%);
  /* 延生线与左侧的距离，根据左侧图形容器的宽度和间距进行调整 */
}

.select-label {
  font-weight: bold;
  font-size: 20px;
}

.select-box {
  /* 样式变更 */
  /* 添加自定义样式以美化下拉框外观 */
  background-color: #f2f2f2;
  border: 2px solid #000000;
  border-radius: 4px;
  padding: 8px;
  font-size: 20px;
  width: 35%;
  margin-bottom: 20px;
  /* 添加下边距 */
}

.select-box0 {
  /* 样式变更 */
  /* 添加自定义样式以美化下拉框外观 */
  background-color: #f2f2f2;
  border: 2px solid #000000;
  border-radius: 4px;
  padding: 8px;
  font-size: 20px;
  width: 50%;
  margin-bottom: 200px;
  /* 添加下边距 */
}
</style>
